const mongoose = require('mongoose')
const User = require('../Models/User')
mongoose.Promise = global.Promise

var promise = mongoose.connect('mongodb://127.0.0.1:27017/BMS', {
  useMongoClient: true // 这个不要省，省了会报错
  /* other options */
})
var db = mongoose.connection
// db.on('error', console.error.bind(console, 'connection error!'))
// db.on('open', console.log.bind(console, 'connection success!'))

module.exports = {
  // 登录
  login (req, res) {
    let username = req.body.username
    let password = req.body.password
    let icode = req.body.icode

    if (!username || !password) {
      return res.status(400).json({message: 'empty username/password!'})
    }

    if (icode !== '1234') {
      return res.status(400).json({message: 'wrong identify code!'})
    }

    User.findByUsername(username, function (err, user) {
      if (err) {
        console.log(err)
        return res.status(400).json({message: `something wrong: ${err}`})
      }

      console.log(user)

      if (!user) {
        return res.status(400).json({message: 'user not register yet, please register first!'})
      }

      if (password !== user.password) {
        return res.status(400).json({message: 'wrong password!'})
      }

      res.cookie('token', JSON.stringify({ id: user._id, username, deadline: Date.now() }), {
        maxAge: 900000,
        // httpOnly: true
      })
      res.status(200).json({message: 'login success', data: user._id})
    })
  },

  logout (req, res) {
    res.clearCookie('token')
    res.status(200).json({message: 'logout'})
  },

  // 注册
  register (req, res) {
    let username = req.body.username
    let password = req.body.password
    let password1 = req.body.password1
    let icode = req.body.icode

    if (!username || !password) {
      return res.json({message: 'empty username/password!'})
    }

    if (icode !== '1234') {
      return res.json({message: 'wrong identify code!'})
    }

    if (password !== password1) {
      return res.json({message: 'twice password are different!'})
    }

    let userInfo = new User({
      username: username,
      password: password
    })
    userInfo.save(e => {
      if (e) {
        return res.json({message: 'fail to save!'})
      }
      res.json({message: 'register success'})
    })
    console.log(userInfo)
  },

  // 查看所有用户
  showUsers (req, res) {
    User.fetch(function (err, user) {
      if (err) {
        console.log(err)
        return res.json({code: -1, message: `something wrong: ${err}`})
      }
      res.json({code: 0, data: user})
    })
  }
}
